<!--#include file="lib/utf-8.asp"-->
<!--#include file="lib/connopen.asp"-->
<!--#include file="lib/asp-common-lib.asp"-->
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>报关单登记系统</title>
<!--#include file="lib/plugins.asp"-->
<script type="text/javascript" src="lib/jquery.upload/jquery.upload-1.0.js"></script>
<script type="text/javascript" src="lib/jquery.dialogextend/jquery.dialogextend.1_0_1.js"></script>

<style type="text/css">
  .ui-datepicker table {
    border: 0;
  }
  tbody th{
    text-align:center;
  }
  #tmp{
    font-family:宋体;
  }
  .formError .formErrorContent{
    font-size:12px;
    width:100%
  }
  .icon{
    border: 1px solid #DDD;
    border-radius: 4px 4px 4px 4px;
    display: block;
    float: left;
    margin: 0 3px;
    padding: 3px 0;
    position: relative;
    cursor:pointer;
    left:2px;
    
  }
  .icon:hover{
    border: 1px solid #222;
    background-color:#DDD;
  }
  .icon-close{
    background-image: url("lib/jquery.ui-v1.9.1/css/smoothness/images/ui-icons_888888_256x240.png");
    background-position: -96px -128px;
    display: block;
    height: 16px;
    margin: 0 3px;
    width: 16px;
  }
  .icon-close:hover{
    background-image: url("lib/jquery.ui-v1.9.1/css/smoothness/images/ui-icons_222222_256x240.png");
  }
  #newbox{
    height:24px;
    padding-top:3px;
  }
  .columnar fieldset div.type-button {
    padding-left: 0.5em;
  }
  .boxcheck{
    background: #A66;
  }
  #tabs{
    margin:0 0 1em 0;
  }
  #tabs,#tabs .ui-corner-all,#tabs .ui-corner-top{
    border-radius:0;
  }
  
  #tabs .ui-widget-content a { color:#4D87C7; background:transparent; text-decoration:none; }
  #tabs .ui-widget-content a:visited  { color:#036; }

  /* (en) maximum constrast for tab focus - change with great care */
  /* (en) Maximaler Kontrast für Tab Focus - Ändern Sie diese Regel mit Bedacht */
  #tabs .ui-widget-content a:focus { text-decoration:underline; color:#000; background: #fff; outline: 3px #f93 solid; }
  #tabs .ui-widget-content a:hover,
  #tabs .ui-widget-content a:active { color:#182E7A; text-decoration:underline; outline: 0 none; }
  #tabs{
    font-size:1em;
    font-family:Arial, Helvetica, sans-serif;
  }
  #detail input[type=text]{
    text-align:right;
    padding-right:1px;
  }
  #tabs{
    display:none;
  }
  #wtr{
    display:none;
  }
  .ui-autocomplete {
        max-height: 500px;
        overflow-y: auto;
        /* prevent horizontal scrollbar */
        overflow-x: hidden;
    }
    /* IE 6 doesn't support max-height
     * we use height instead, but this forces the menu to always be this tall
     */
    * html .ui-autocomplete {
        height: 500px;
    }
</style>
<script type="text/javascript">
  $(function() {
    $.ajaxSetup ({
      cache: false, //关闭AJAX相应的缓存
      beforeSend:function() {
        $("#form1 input[type='submit']").prop("disabled",true);
      },
      complete:function() {
        $("#form1 input[type='submit']").prop("disabled",false);
      }
    });
  
    $("#form1,#fm_uploadinvoice").validationEngine('attach',{
        validationEventTrigger:'submit'
    });
    $(".datepicker").datepicker();
    $("#print_process").click(function(){
      window.open('process_print.asp?id='+$("#id").val(), '_blank', 'height=768px, width=1024px, scrollbars=yes, resizable=yes');
    });
    $("#submit_del").click(function(){
      return confirm('确定删除这张报关单吗？\n这将导致所有与此保管单关联的数据被删除！');
    });
    
    var json_tmp,json_wtrfeetmp,json_wtrroleuser;
    $("#chk_detail").prop("checked") ? $("#detail").show() : $("#detail").hide()
    $("#chk_detail").click(function(){
      $(this).prop("checked") ? $("#detail").show() : $("#detail").hide()
    });
    
    $("#form1").keypress(function(e) {
      if (e.which == 13 || e.keyCode==13 ) // 判断所按是否回车键
      {
        //e.keyCode=9;
        return false;// 取消默认的提交行为
      }
    });
    $("#detail input:text").keypress(function(e) {
      if (e.which == 13 || e.keyCode==13 ) // 判断所按是否回车键
      {
        var inputs = $("#detail").find(":text");                   //获取表单中的所有输入框
        var idx = inputs.index(this);      //获取当前焦点输入框所处的位置
        //if (idx == inputs.length - 1)     // 判断是否是最后一个输入框
        //{
        //if (confirm("最后一个输入框已经输入,是否提交?"))   //用户确认
        //$("#myform").submit();    //提交表单
        //}
        //else{
          inputs[idx + 1].focus();       //设置焦点
          inputs[idx + 1].select();       //选中文字
        //}
        //return false;// 取消默认的提交行为
      }
    });

    $.getJSON("json_tmp.asp",function(data){
      json_tmp=data;
      var tmp_option="";
      $.each(json_tmp,function(i,item){
        tmp_option+='<option value="'+item.id+'">'+FillSpace(item.id,16)+FillSpace(item.receive,16)+item.pay+'</option>';
      });
      $("#tmp").append(tmp_option);
      //$("#tmp").attr("value",$("#wtr").find("option:selected").attr("title"));
      $("#tmp").val($("#wtr").find("option:selected").attr("title"));
      if($("#form1 input[name=submit]").val()=="新增"){
        $("#tmp").trigger("change");
      }
    });
    $.getJSON("json_wtrfeetmp.asp",function(data){
      json_wtrfeetmp=data;
    });
    $.getJSON("json_wtrroleuser.asp",function(data){
      json_wtrroleuser=data;
    });
    $("#tmp").change(function(){
      find_tmp=false;
      tmp_id=$(this).val();
      $.each(json_tmp,function(i,item){
        if(item.id==tmp_id){
          $("#cd_receive").val(item.receive);
          $("#cd_pay").val(item.pay);
          $("#total_receive").val(calc_total_receive());
          $("#total_pay").val(calc_total_pay());
          find_tmp=true;
          return false;
        }
      });
      if(!find_tmp){
        $("#cd_receive").val("");
        $("#cd_pay").val("");
        $("#total_receive").val(calc_total_receive());
        $("#total_pay").val(calc_total_pay());
      }
    });
    
    function switch_passfee(){
        var bpassfee,wtrid,feer,feep;
        $("#cd_passfee").prop("checked") ? bpassfee=true : bpassfee=false;
        wtrid=$("#wtr").val();
        for(var i=0;i<json_wtrfeetmp.length;i++){
            var feerow=json_wtrfeetmp[i];
            if(wtrid==feerow.wtrid){
                if(feerow.feeid==6){
                    if(bpassfee){
                        feer=feerow.feer;
                        feep=feerow.feep;
                        if(feer>0){
                            $("#detailr_"+feerow.feeid).val(feer);
                            $("#detailr_"+feerow.feeid).css("background-color","red");
                        }
                        if(feep>0){
                            $("#detailp_"+feerow.feeid).val(feep);
                            $("#detailp_"+feerow.feeid).css("background-color","red");
                        }
                    }else{
                        feer=0;
                        feep=0;
                        $("#detailr_"+feerow.feeid).val("");
                        $("#detailp_"+feerow.feeid).val("");
                        $("#detailr_"+feerow.feeid).css("background-color","white");
                        $("#detailp_"+feerow.feeid).css("background-color","white");
                    }
                }
            }
        }
    }
    
    //换单费切换
    $("#cd_passfee").click(function(){
        switch_passfee();
    });
    
    $("#reset").click(function(){
        $("#detail input").css("background-color","white");
    });
    //委托人附加费模板函数
    function do_wtrfeetmp(wtrid){
        //console.log(wtrid);
        var bShowDivDetail,gc,lc,feer,feep,bpassfee;
        gc=$("#cd_goodscount").val();
        lc=0;
        if(gc>5&&gc<=20){
            lc=Math.ceil(gc/5);
        }
        $("#cd_passfee").prop("checked") ? bpassfee=true : bpassfee=false;
        $("#chk_detail").prop("checked") ? bShowDivDetail=true : bShowDivDetail=false;
        $("#detail input").css("background-color","white");
        for(var i=0;i<json_wtrfeetmp.length;i++){
            var feerow=json_wtrfeetmp[i];
            if(wtrid==feerow.wtrid){
                bShowDivDetail=true;
                if(feerow.feeid==24){
                    feer=feerow.feer*lc;
                    feep=feerow.feep*lc;
                }else if(feerow.feeid==6&&!bpassfee){
                    feer=0;
                    feep=0;
                }else{
                    feer=feerow.feer;
                    feep=feerow.feep;
                }
                if(feer>0){
                    $("#detailr_"+feerow.feeid).val(feer);
                    $("#detailr_"+feerow.feeid).css("background-color","red");
                }
                if(feep>0){
                    $("#detailp_"+feerow.feeid).val(feep);
                    $("#detailp_"+feerow.feeid).css("background-color","red");
                }
            }
        }
        if(bShowDivDetail){
            $("#chk_detail").prop("checked",true);
            $("#detail").show();
        }else{
            $("#chk_detail").prop("checked",false);
            $("#detail").hide();
        }
    }
    
    function do_wtrroleuser(wtrid){
        $("select[name='userid']").val(0);
        for(var i=0;i<json_wtrroleuser.length;i++){
            row=json_wtrroleuser[i];
            if(row.wtrid==wtrid){
                $("#roleid-"+row.roleid).val(row.userid);
            }
        }
    }
    
    
    $("#wtr").change(function(){
      $("#form1 input[type='submit']").prop("disabled",true);

      //alert($(this).find("option:selected").attr("title"));
      //$("#tmp").attr("value",$(this).find("option:selected").attr("title"));
      $("#tmp").val($(this).find("option:selected").attr("title"));
      
      //对委托人附加费模板做响应
      do_wtrfeetmp($(this).val());
      
      //对委托人的角色做相应
      do_wtrroleuser($(this).val());
      
      $("#tmp").trigger("change");
      
      $("#form1 input[type='submit']").prop("disabled",false);
    });
    $("input[name=cd_status]").click(function(){
      $("#vote2,#vote3").next().next().html("");
      $(this).next().next().html((new Date()).toLocaleDateString());
    });
    function isnumber(s){
      s=$.trim(s);
      if(isNaN(s)||s==""){
        return false;
      }else{
        return true;
      }
    }
    function tonumber(s){
      if(isnumber(s)){
        s=parseFloat(s);
      }else{
        s=0;
      }
      return s;
    }
    function calc_total_receive(){
      var cd_receive,cy_receive,sj_receive,jk_receive,qt_receive;
      cd_receive=tonumber($.trim($("#cd_receive").val()));
      cy_receive=tonumber($.trim($("#cy_receive").html()));
      sj_receive=tonumber($.trim($("#sj_receive").html()));
      jk_receive=tonumber($.trim($("#jk_receive").html()));
      qt_receive=tonumber($.trim($("#qt_receive").html()));
      return cd_receive+cy_receive+sj_receive+jk_receive+qt_receive;
    }
    function calc_total_pay(){
      var cd_pay,cy_pay,sj_pay,jk_pay,qt_pay;
      cd_pay=tonumber($.trim($("#cd_pay").val()));
      cy_pay=tonumber($.trim($("#cy_pay").html()));
      sj_pay=tonumber($.trim($("#sj_pay").html()));
      jk_pay=tonumber($.trim($("#jk_pay").html()));
      qt_pay=tonumber($.trim($("#qt_pay").html()));
      return cd_pay+cy_pay+sj_pay+jk_pay+qt_pay;
    }
    function calc_total(){
        calc_total_receive();
        calc_total_pay();
    }
    
    //$("#total_receive").val(calc_total_receive());
    //$("#total_pay").val(calc_total_pay());
    $("#cd_receive,#cd_pay").bind("keyup blur",function(){
      $("#total_receive").val(calc_total_receive());
      $("#total_pay").val(calc_total_pay());
    });
    
    function calc_detail(i){
      var t=0;
      $("#detail tr td:nth-child("+i+")>input").each(function(){
        v=$.trim($(this).val());
        if(isnumber(v)){
          v=parseFloat(v);
        }else{
          v=0;
        }
        t+=v;
      });
      return t;
    }
    
// 新的计算方法    
    $("#detail").data([
        {"ColName":"cy_receive","ColVal":2,"ColCate":"receive"},
        {"ColName":"cy_pay","ColVal":3,"ColCate":"pay"},
        {"ColName":"sj_receive","ColVal":5,"ColCate":"receive"},
        {"ColName":"sj_pay","ColVal":6,"ColCate":"pay"},
        {"ColName":"jk_receive","ColVal":8,"ColCate":"receive"},
        {"ColName":"jk_pay","ColVal":9,"ColCate":"pay"},
        {"ColName":"qt_receive","ColVal":11,"ColCate":"receive"},
        {"ColName":"qt_pay","ColVal":12,"ColCate":"pay"},
    ]);
    //console.log($("#detail").data());
    $.each($("#detail").data(),function(i,item){
        $("#"+item["ColName"]).html(calc_detail(item["ColVal"]));
        $("#detail tr td:nth-child("+item["ColVal"]+")>input").bind("keyup blur",function(){
            $("#"+item["ColName"]).html(calc_detail(item["ColVal"]));
            if(item["ColCate"]=="receive"){
                $("#total_"+item["ColCate"]).val(calc_total_receive());
            }
            if(item["ColCate"]=="pay"){
                $("#total_"+item["ColCate"]).val(calc_total_pay());
            }

        });
    });

/*    老的计算方法
    $("#cy_receive").html(calc_detail(2));
    $("#cy_pay").html(calc_detail(3));
    $("#sj_receive").html(calc_detail(5));
    $("#sj_pay").html(calc_detail(6));
    $("#jk_receive").html(calc_detail(8));
    $("#jk_pay").html(calc_detail(9));
    $("#qt_receive").html(calc_detail(11));
    $("#qt_pay").html(calc_detail(12));
    
    
    $("#detail tr td:nth-child(2)>input").bind("keyup blur",function(){
      $("#cy_receive").html(calc_detail(2));
      $("#total_receive").val(calc_total_receive());
    });
    $("#detail tr td:nth-child(3)>input").bind("keyup blur",function(){
      $("#cy_pay").html(calc_detail(3));
      $("#total_pay").val(calc_total_pay());
    });
    $("#detail tr td:nth-child(5)>input").bind("keyup blur",function(){
      $("#sj_receive").html(calc_detail(5));
      $("#total_receive").val(calc_total_receive());
    });
    $("#detail tr td:nth-child(6)>input").bind("keyup blur",function(){
      $("#sj_pay").html(calc_detail(6));
      $("#total_pay").val(calc_total_pay());
    });
    $("#detail tr td:nth-child(8)>input").bind("keyup blur",function(){
      $("#jk_receive").html(calc_detail(8));
      $("#total_receive").val(calc_total_receive());
    });
    $("#detail tr td:nth-child(9)>input").bind("keyup blur",function(){
      $("#jk_pay").html(calc_detail(9));
      $("#total_pay").val(calc_total_pay());
    });
    $("#detail tr td:nth-child(11)>input").bind("keyup blur",function(){
      $("#qt_receive").html(calc_detail(11));
      $("#total_receive").val(calc_total_receive());
    });
    $("#detail tr td:nth-child(12)>input").bind("keyup blur",function(){
      $("#qt_pay").html(calc_detail(12));
      $("#total_pay").val(calc_total_pay());
    });
*/
    
    //$(".res").live('click',function(e){
    //  e.preventDefault();//阻止a的原先事件
    //});
    
    if($("#employee").val()=="False"){
      //console.log(1);
      $div_receive=$("#total_receive").parent();
      $div_receive.closest(".error").remove();
      $("#cd_receive").parent().parent().after($("<div />").addClass("c33r").append($div_receive));
    }
    
    $('.icon').live('click',function(){
        if(confirm('确定删除集装箱号:'+$(this).closest('div.c20l').find('input').val()+'？')){
            $(this).closest('div.c20l').remove();
        }
    });
    $('#newbox').click(function(){
    
        h='<div class="c20l">';
        h+='<div class="type-text">';
        h+='<input id="box" name="box" class="validate[custom[onlyUcaseLetterNumber],minSize[11],maxSize[11]]" type="text" size="11" maxlength="11" value="" />';
        h+='<div class="icon"><span class="icon-close"></span></div>';
        h+='</div>';
        h+='</div>';
        //alert(h);
    
        $(this).closest('div.c20l').before(h);
    })
    //系统同步的单子或手工输入的单子不在输入岗位就不能新增、修改、删除集装箱
    if($("#cd_post").val()!=1||$("#cd_synmode").val()==1){
        $("#newbox,.icon").hide();
        $("input[name='box']").attr("readonly","readonly");
    }
    
    
//    $('#invoicefile').fileupload({
//        url:'upload_invoice.asp',
//        dataType: 'json',
//        formData:'',
//        done: function (e, data) {
//           $.each(data.result, function (index, file) {
//                $('<p/>').text(file.name).appendTo(document.body);
//            });
//        }
//    });


    $("#invoice").click(function(){
      $("#dv_uploadinvoice").dialog("open");
    });
    $("#dv_uploadinvoice").dialog({
      autoOpen: false,
      minHeight:200,
      modal: true,
      position: { my: "center center", at: "center center" },
      buttons: {
        "确定": function() {
          if($("#fm_uploadinvoice").validationEngine('validate')){
            $("#fm_uploadinvoice").trigger("submit");
            
           
//            $.upload({
//                    // 上传地址
//                    url: 'upload_invoice.asp', 
//                   // 文件域名字
//                    fileName: 'invoice_file', 
                    // 其他表单数据
//                    params: {name: 'pxblog'},
                    // 上传完成后, 返回json, text
//                    dataType: 'json',
                    // 上传之前回调,return true表示可继续上传
//                    onSend: function() {
//                            return true;
//                    },
                    // 上传之后回调
//                    onComplate: function(data) {
//                            alert(data);
//                    }
//            });
            
         
          }
        },
        "取消": function() {
          $(this).dialog( "close" );
        }

      }
    });




    /*
    $(".res").live('click',function(e){//对分页栏中的a元素进行操作
      e.preventDefault();//阻止a的原先事件
      opt_id=$(this).attr('href');
      $.get("res.asp?opt_id="+opt_id,function(data){//用ajax的get方式提交
        $(".res").tooltip({
          open: function() {
          var tooltip = $(this).tooltip("widget");
          $(document).mousemove(function(event) {
            tooltip.position({
              my: "left center",
              at: "right center",
              offset: "15 25",
              of: event
            });
          })
          // trigger once to override element-relative positioning
          .mousemove();
        },
        close: function() {
          $(document).unbind("mousemove");
      }

        
        });
      });
    });
    */
    
    //console.log($(window).width());
    //console.log($(document).width());
    if($(window).width()<1024){
        $("#col1").hide();
        $("#col3").css("margin","0");
        
    }
    $("#html_file").click(function(){
      window.open('htmlfile.asp?id='+$("#id").val(), '_blank');
    });
    //$("#pdf_file").click(function(){
    //  window.open('pdffile.asp?id='+$("#id").val(), '_blank');
    //});
    
    $(".del_invoice").click(function(e){
        e.preventDefault();
        var invoiceid;
        invoiceid=$(this).prev().val();
        $invoicetr=$(this).closest('tr');
        if(confirm('确定删除这张发票吗？')){
            $.post("del_invoice.asp",{id:invoiceid},function(data){
                if(data){
                    if(data.bStatus){
                        //console.log($invoicetr.html());
                        $invoicetr.remove();
                    }
                    alert(data.sInfo);
                }
            });
        }
    });
    
    
    cd_no=$("#cd_no").val();
    function changeSource(){
        $sel=$("#cd_source").find("option:selected");
        if($sel.text()=="ATA"){
            $("#cd_no").prop({"maxlength":14,"class":"validate[required,custom[onlyATANo],minSize[14],maxSize[14]]"});
        }else{
            $("#cd_no").prop({"maxlength":18,"class":"validate[required,custom[onlyNumber],minSize[18],maxSize[18]]"});
        }
        if($sel.text()=="重箱出卡"){
            $("#cd_no").val("000000000000000000");
        }else{
            $("#cd_no").val(cd_no);
        }

    }
    changeSource();
    $("#cd_source").change(function(){
        changeSource();
    });
    
    $("#dv_todolist").dialog({
      autoOpen: false,
      dialogClass: "dialogTodo",
      //draggable: true,
      resizable: false,
      minHeight:50,
      //width:400,
      modal: false,
      position: { my: "left bottom", at: "left bottom" }
    }).dialogExtend({
        "close":false,
        //"titlebar":"transparent",
        "minimize":true
    });
    $("#dv_todolist").dialog("open");

    
    //$(".tabs").accessibleTabs({fx:"show",fxspeed: null, tabhead: 'h3', syncheights: true});
    
    $( "#tabs" ).tabs({
        beforeLoad: function( event, ui ) {
            ui.jqXHR.error(function() {
                ui.panel.html(
                    "标签页加载错误，请联系管理员解决。" );
            });
        },      
        load: function (e, ui) {
            $(ui.panel).find(".tab-loading").remove();
        },
        select: function (e, ui) {
            var $panel = $(ui.panel);

            if ($panel.is(":empty")) {
                $panel.append("<div class='tab-loading'>Loading...</div>")
            }
        }
    }).show();
    
    var json_wtr;
    $.getJSON("json_wtr.asp",function(data){
      json_wtr=data;
      //for(var i=0;i<data.length;i++){
      //  if(data[i].id==$("#wtr").val()){
      //      $("#acwtr").val(data[i].label);
      //  }
      //}
      $( "#acwtr" ).autocomplete({
            source: function(request, response){
                var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
                response( $.grep( data, function( value ) {
                    return matcher.test(value.value) || matcher.test(value.label);
                }) );
            },
            minLength: 0,
            delay:0,
            select:function(event,ui){
                $(this).val(ui.item.label);
                $(this).css('color','');
                //console.log(ui.item.label);
                $("#wtr").val(ui.item.id);
                $("#wtr").trigger('change');
                return false;
            },
            change: function( event, ui ) {
                        if ( !ui.item ) {
                            // no item selected
                            //$(this).prev().val('0');
                            $(this).css('color','red');
                        }else{
                            $(this).css('color','');
                        }
                    }
        }).bind('dblclick',function() {
            $(this).autocomplete("search","");
        });
      
    });
    

    
  });
</script>
<!--#include file="lib/js-google-analytics.asp"-->
</head>
<%
if not CheckLogin() then call JumpErrorPage(3)
id=saferequest("id",1)
if id="" then id=0 else id=clng(id)
rcd=saferequest("rcd",0)
submit=saferequest("submit",0)
if id=0 then
  '初始化空白单
  action="add"
  '初始化日期
  cd_date=date()
  cd_settledate=cd_date
  '初始化岗位
  cd_post=1
else
  ' 记录查看报关单，id不空，submit要空
  if rcd<>"no" and submit="" then call SimpleRecord("cd",id,"查看","成功",session("iId"),session("iClientId"),false)

  action="edit"
end if
' bt_act=request("bt_act")
' if bt_act<>"" then
  ' cd_actreceive=request("cd_actreceive")
  ' cd_actpay=request("cd_actpay")
  ' if bt_act="已收" then sql_act="update cd set cd_received=true,cd_actreceive="&cd_actreceive&" where id="&id
  ' if bt_act="已付" then sql_act="update cd set cd_paid=true,cd_actpay="&cd_actpay&" where id="&id
  ' call ExecuteCommand(sql_act,false)
' end if

if submit<>"" then
  fee_act=false
  '事务开始
  conn.BeginTrans
  on error resume next
  action=request("action")
  wtr=request("wtr")
  bwtr=request("bwtr")
  category=request("category")
  cd_no=request("cd_no")
  cd_date=request("cd_date")
  cd_settledate=request("cd_settledate")
  cd_company=trim(request("cd_company"))
  cd_voyage=UCase(trim(request("cd_voyage")))
  cd_lading=UCase(trim(request("cd_lading")))
  cd_verify=request("cd_verify")
  '防止核销选项没有选中，设置默认为未退
  cd_status=request("cd_status")
  if cd_status="" then cd_status=1
  cd_statusdate=date()
  cd_receive=request("cd_receive")
  cd_pay=request("cd_pay")
  ' cd_actreceive=request("cd_actreceive")
  ' cd_actpay=request("cd_actpay")
  cd_post=request("cd_post")
  username=session("iId")
  cd_update=Now()
  cd_passno=request("cd_passno")
  cd_sealno=request("cd_sealno")
  cd_orderno=UCase(trim(saferequest("cd_orderno",0)))
  cd_boxno=UCase(trim(request("cd_boxno")))
  cd_memo=request("cd_memo")
  cd_check=request("cd_check")
  if cd_check<>"" then cd_check=1 else cd_check=0
  cd_synmode=request("cd_synmode")
  cd_source=request("cd_source")
  cd_passfee=request("cd_passfee")
  if cd_passfee<>"" then cd_passfee=1 else cd_passfee=0
  
  if submit="提交" then
    '作业岗位2上如果无详细费用提交至4反之提交至3
    if not HasFee and cd_post=2 then cd_post=cd_post+1
    cd_post=cd_post+1
  end if
  if submit="退回" then
    '财务岗位4上如果无详细费用退回至2反之回退至3
    if not HasFee and cd_post=4 then cd_post=cd_post-1
    cd_post=cd_post-1
  end if
  if action="edit" then
    operate="编辑"
    '如果是编辑状态，提交或保存按钮把所有信息更新
    if submit="保存" or submit="提交" then
      sql_act="update cd set wtr="&wtr&",bwtr="&bwtr&",category="&category&",cd_no='"&cd_no&"',cd_date='"&cd_date&"',cd_settledate='"&cd_settledate&"',cd_company='"&cd_company&"',cd_voyage='"&cd_voyage&"',cd_lading='"&cd_lading&"',cd_verify='"&cd_verify&"',cd_receive="&cd_receive&",cd_pay="&cd_pay&",cd_post="&cd_post&",cd_passno='"&cd_passno&"',cd_sealno='"&cd_sealno&"',cd_orderno='"&cd_orderno&"',cd_boxno='"&cd_boxno&"',cd_update='"&cd_update&"',cd_memo='"&cd_memo&"',cd_check="&cd_check&",cd_source="&cd_source&",cd_passfee="&cd_passfee&" where id="&id
      '一旦进入编辑状态，先全部删除集装箱号
      
      ' sql_box="delete * from cdbox where cd="&id
      ' call ExecuteCommand(sql_box,false)
      ' call AddBox(id)
      
      '一旦进入编辑状态，先全部删除详细费用
      ' sql_delfee="delete * from fee where cd="&id
      ' call ExecuteCommand(sql_delfee,false)
      ' call AddFee()
      fee_act=true
      ' 操作用户角色
      call CdRoleUser(id)
    end if
    if submit="复制" then
        operate="复制"

        sql_act="insert into cd(wtr,bwtr,category,cd_no,cd_date,cd_settledate,cd_company,cd_voyage,cd_lading,cd_verify,cd_post,username,cd_passno,cd_orderno,cd_sealno,cd_boxno,cd_memo,cd_check,cd_synmode,cd_source,cd_passfee) values("&wtr&","&bwtr&","&category&",'"&cd_no&"','"&cd_date&"','"&cd_settledate&"','"&cd_company&"','"&cd_voyage&"','"&cd_lading&"','"&cd_verify&"',1,"&username&",'"&cd_passno&"','"&cd_sealno&"','"&cd_orderno&"','"&cd_boxno&"','"&cd_memo&"',"&cd_check&",2,6,false)"
        
        id=ExecuteCommand(sql_act,true)
        call SimpleRecord("cd",id,operate,"成功",session("iId"),session("iClientId"),false)
        ' call AddBox(id)
        ' call AddFee()
        ' 操作用户角色
        ' call CdRoleUser(id)
    end if
    
    '如果是编辑状态，退回按钮只修改cd_post状态
    if submit="退回" then
      sql_act="update cd set cd_post="&cd_post&",cd_update='"&cd_update&"',cd_confirm=false where id="&id
    end if
    '核销单管理只能修改核销单状态
    if submit="核销" then
      sql_act="update cd set cd_post="&cd_post&",cd_status="&cd_status&",cd_statusdate='"&cd_statusdate&"',cd_update='"&cd_update&"' where id="&id
    end if
    if submit="已收" then
      cd_actreceive=request("cd_actreceive")
      sql_act="update cd set cd_received=true,cd_actreceive="&cd_actreceive&",cd_update='"&cd_update&"' where id="&id
    end if
    if submit="已付" then
      cd_actpay=request("cd_actpay")
      sql_act="update cd set cd_paid=true,cd_actpay="&cd_actpay&",cd_update='"&cd_update&"' where id="&id
    end if
    if submit="确认" then
      sql_act="update cd set cd_confirm=true,cd_update='"&cd_update&"' where id="&id
    end if
    if submit="删除" and CheckPostFlag(session("aaPostFlag"),cd_post,5) then
      sql_act="delete from cd where (not (cd_received or cd_paid)) and id="&id
      operate="删除"
      fee_act=true
      call ExecuteCommand("delete * from cdroleuser where cdid="&id,false)
    end if
    if submit="隐藏" then
      sql_act="update cd set cd_hidden=true,cd_update='"&cd_update&"' where id="&id
    end if
    if submit="显示" then
      sql_act="update cd set cd_hidden=false,cd_update='"&cd_update&"' where id="&id
    end if
    call OperateRecord(sql_act,fee_act,"cd",id,operate,submit)
  end if
  
  if action="add" then
    operate="新增"
    '如果是添加状态，新增和提交按钮起同样作用
    sql_act="insert into cd(wtr,bwtr,category,cd_no,cd_date,cd_settledate,cd_company,cd_voyage,cd_lading,cd_verify,cd_receive,cd_pay,cd_post,username,cd_passno,cd_sealno,cd_orderno,cd_boxno,cd_memo,cd_check,cd_synmode,cd_source,cd_passfee) values("&wtr&","&bwtr&","&category&",'"&cd_no&"','"&cd_date&"','"&cd_settledate&"','"&cd_company&"','"&cd_voyage&"','"&cd_lading&"','"&cd_verify&"',"&cd_receive&","&cd_pay&","&cd_post&","&username&",'"&cd_passno&"','"&cd_sealno&"','"&cd_orderno&"','"&cd_boxno&"','"&cd_memo&"',"&cd_check&","&cd_synmode&","&cd_source&","&cd_passfee&")"
    fee_act=true
    id=OperateRecord(sql_act,fee_act,"cd",0,operate,submit)
    
    call AddBox(id)
    ' call AddFee()
    ' 操作用户角色
    call CdRoleUser(id)
  end if



  
  ' 操作用户角色
  function CdRoleUser(id)
    dim roleid,roleids,userid,userids,i,sql_adduser
    roleid=saferequest("roleid",0)
    roleids=split(trim(roleid),",")
    userid=saferequest("userid",0)
    userids=split(trim(userid),",")

    call ExecuteCommand("delete * from cdroleuser where cdid="&id,false)
    for i=0 to Ubound(roleids)
        if userids(i)<>0 then
            sql_adduser="insert into cdroleuser(cdid,roleid,userid) values("&id&","&roleids(i)&","&userids(i)&")"
            call ExecuteCommand(sql_adduser,false)
        end if
    next
  
  end function
  
  
  
  function OperateRecord(sql_act,fee_act,re_table,re_id,re_operate,re_memo)
    dim aField,aFieldName,sSelectColumn,iFieldCount
    dim sql_sel,opt_id,rs_old,rs_new
    dim aaSourceValue,aaDestValue
    
    dim aaFeeSource,aaFeeDest,sFeeSource,sFeeDest,sFeeFieldName
    dim rs_feeold,rs_feenew,sql_fee,sql_delfee
    
    aField=dCdTable.keys
    aFieldName=dCdTable.items
    sSelectColumn=join(aField,",")
    iFieldCount=ubound(aField)
    
    ' 保存原始数据
    sql_sel="select "&sSelectColumn&" from cdfee inner join post on cdfee.cd_post=post.id where cdfee.id="&re_id
    set rs_old=server.createobject("adodb.recordset")
    rs_old.open sql_sel,conn,1,1
    if rs_old.bof and rs_old.eof then
      redim aaSourceValue(iFieldCount,0)
    else
      aaSourceValue=rs_old.getrows(,,aField)
    end if
    rs_old.close
    set rs_old=nothing

    ' 保存原始fee数据
    if fee_act then
      sql_fee="select catedetail.catename+':'+catedetail.feename as feename ,iif(isnull(fee.receive) or fee.receive=0,'',fee.receive) as receive,iif(isnull(fee.pay) or fee.pay=0,'',fee.pay) as pay from catedetail left join fee on (fee.detail=catedetail.id and fee.cd="&re_id&") order by catedetail.cateid,catedetail.id"
      set rs_feeold=server.createobject("adodb.recordset")
      rs_feeold.open sql_fee,conn,1,1
      if not(rs_feeold.bof and rs_feeold.eof) then
        aaFeeSource=rs_feeold.getrows()
        sql_delfee="delete * from fee where cd="&re_id
        call ExecuteCommand(sql_delfee,false)
      end if
      rs_feeold.close
      set rs_feeold=nothing
    end if

    ' 执行原数据表的sql操作，如果是insert操作，返回新插入的id，否则直接提交
    if lcase(left(ltrim(sql_act),6))="insert" then
      re_id=ExecuteCommand(sql_act,true)
    else
      call ExecuteCommand(sql_act,false)
    end if
    
    ' 增加fee操作，如果是删除报关单，则无需增加fee
    if not lcase(left(ltrim(sql_act),6))="delete" and fee_act then call AddFee(re_id)
    
    ' 执行主操作记录表
    ' sql_opt="insert into record(re_table,re_id,re_operate,re_memo,username,re_clientip,re_clienthost,re_clientagent) values('"&lcase(re_table)&"',"&re_id&",'"&re_operate&"','"&re_memo&"',"&session("iId")&",'"&Request.ServerVariables("remote_addr")&"','"&Request.ServerVariables("remote_host")&"','"&Request.ServerVariables("http_user_agent")&"')"
    
    
    ' iClientId=OperateClient(session("iId"))
    
    
    ' sql_opt="insert into record(re_table,re_id,re_operate,re_memo,username,re_clientid) values('"&lcase(re_table)&"',"&re_id&",'"&re_operate&"','"&re_memo&"',"&session("iId")&","&session("iClientId")&")"
    ' opt_id=ExecuteCommand(sql_opt,true)
    
    opt_id=SimpleRecord(re_table,re_id,re_operate,re_memo,session("iId"),session("iClientId"),true)
    
    '更新操作后马上读取新信息
    sql_sel="select "&sSelectColumn&" from cdfee inner join post on cdfee.cd_post=post.id where cdfee.id="&re_id
    set rs_new=server.createobject("adodb.recordset")
    rs_new.open sql_sel,conn,1,1
    if rs_new.bof and rs_new.eof then
      redim aaDestValue(iFieldCount,0)
    else
      aaDestValue=rs_new.getrows(,,aField)
    end if
    rs_new.close
    set rs_new=nothing
    
    ' 获取操作后fee的情况
    if fee_act then
      sql_fee="select catedetail.catename+':'+catedetail.feename as feename ,iif(isnull(fee.receive) or fee.receive=0,'',fee.receive) as receive,iif(isnull(fee.pay) or fee.pay=0,'',fee.pay) as pay from catedetail left join fee on (fee.detail=catedetail.id and fee.cd="&re_id&") order by catedetail.cateid,catedetail.id"
      set rs_feenew=server.createobject("adodb.recordset")
      rs_feenew.open sql_fee,conn,1,1
      if not(rs_feenew.bof and rs_feenew.eof) then
        aaFeeDest=rs_feenew.getrows()
      end if
      rs_feenew.close
      set rs_feenew=nothing
    end if
    
    '开始循环判断cd表的不同之处
    dim i
    for i=0 to iFieldCount
      if aaDestValue(i,0)<>aaSourceValue(i,0) then
        sql_record="insert into records(opt_id,res_source,res_dest,res_fieldname) values ("&opt_id&",'"&aaSourceValue(i,0)&"','"&aaDestValue(i,0)&"','"&aFieldName(i)&"')"
        call ExecuteCommand(sql_record,false)
      end if
    next
    
    ' 开始循环判断fee表的变更情况
    if fee_act then
      dim j
      if IsArray(aaFeeDest) and IsArray(aaFeeSource) then
        for i=0 to ubound(aaFeeSource,2)
          for j=1 to 2
            if j=1 then sFeeFieldName="(应收)"
            if j=2 then sFeeFieldName="(应付)"
            if aaFeeSource(j,i)<>aaFeeDest(j,i) then
              sFeeSource=aaFeeSource(j,i)
              sFeeDest=aaFeeDest(j,i)
              sFeeFieldName=aaFeeSource(0,i)&sFeeFieldName
              sql_record="insert into records(opt_id,res_source,res_dest,res_fieldname) values ("&opt_id&",'"&sFeeSource&"','"&sFeeDest&"','"&sFeeFieldName&"')"
              call ExecuteCommand(sql_record,false)
            end if
          next
        next
      end if
    end if
    
    OperateRecord=re_id
  end function
  
  
  
  function HasFee()
    dim i,c
    HasFee=false
    c=request.form("detailid").count
    for i=1 to c
      detailid=request.form("detailid")(i)
      detailr=request.form("detailr_"&detailid)
      detailp=request.form("detailp_"&detailid)
      if IsNumberNz(detailr) or IsNumberNz(detailp) then
        HasFee=true
        exit function
      end if
    next
  end function

  
  function AddFee(id)
    dim c,i,detailid,detailr,detailp,sql_addfee
    c=request.form("detailid").count
    'response.write(c)
    for i=1 to c
      detailid=request.form("detailid")(i)
      detailr=request.form("detailr_"&detailid)
      detailp=request.form("detailp_"&detailid)
      'response.write(detailid&"空"&detailr&" "&detailp&"<br />")
      if IsNumberNz(detailr) or IsNumberNz(detailp) then
        if IsNumberNz(detailr) and IsNumberNz(detailp) then
          sql_addfee="insert into fee(cd,detail,receive,pay) values("&id&","&detailid&","&detailr&","&detailp&")"
        else
          if IsNumberNz(detailr) then sql_addfee="insert into fee(cd,detail,receive) values("&id&","&detailid&","&detailr&")"
          if IsNumberNz(detailp) then sql_addfee="insert into fee(cd,detail,pay) values("&id&","&detailid&","&detailp&")"
        end if
        call ExecuteCommand(sql_addfee,false)
      end if
    next
  end function

  function AddBox(id)
    dim c,i,sql_addbox
    
    boxs=split(UCase(trim(request("box"))),",")
    ' response.write(request("box"))
    ' for box=0 to Ubound(boxs)
    ' response.write(boxs(box))
    ' next
    ' response.end
    'response.write(c)
    for i=0 to Ubound(boxs)
        if len(trim(boxs(i)))=11 then
            sql_addbox="insert into cdbox(cd,box) values("&id&",'"&trim(boxs(i))&"')"
            call ExecuteCommand(sql_addbox,false)
        end if
    next
  end function


  
  '老的操作fee表函数，作废
  function OldOperateFee()
    bDelfee=false
    c=request.form("detailid").count
    'response.write(c)
    for i=1 to c
      detailid=request.form("detailid")(i)
      detailr=request.form("detailr_"&detailid)
      detailp=request.form("detailp_"&detailid)
      'response.write(detailid&"空"&detailr&" "&detailp&"<br />")
      if IsNumberNz(detailr) or IsNumberNz(detailp) then
        if action="edit" and not bDelfee then
          '一旦进入编辑状态，先全部删除详细费用
          sql_delfee="delete * from fee where cd="&id
          call ExecuteCommand(sql_delfee,false)
          bDelfee=true
        end if
        if IsNumberNz(detailr) and IsNumberNz(detailp) then
          sql_addfee="insert into fee(cd,detail,receive,pay) values("&id&","&detailid&","&detailr&","&detailp&")"
        else
          if IsNumberNz(detailr) then sql_addfee="insert into fee(cd,detail,receive) values("&id&","&detailid&","&detailr&")"
          if IsNumberNz(detailp) then sql_addfee="insert into fee(cd,detail,pay) values("&id&","&detailid&","&detailp&")"
        end if
        call ExecuteCommand(sql_addfee,false)
      end if
    next
  end function
  
  
  '事务提交
  ' if conn.Errors.Count=0 then 
    ' conn.CommitTrans  '如果没有conn错误，则执行事务提交
  ' else
    ' conn.RollbackTrans '否则回滚
  ' end if

  if err.number=0 then 
    conn.CommitTrans  '如果没有conn错误，则执行事务提交
  else
    conn.RollbackTrans '否则回滚
    '回滚后的其他操作
    'strerr=err.Description
    url=request.ServerVariables("http_host")&request.ServerVariables("url")
    Response.Write "数据库错误！<br /><font color=red>Error # " & CStr(Err.Number) & "<br />" & Err.Description & "<br />Source: " & Err.Source &"<br />错误页面："&url&"</font><br />"
    Response.End
  end if
end if

if operate="删除" then response.redirect("process.asp")
if operate="复制" then response.redirect("process.asp?id="&clng(id))

if id<>0 then
  sql = "select * from cdfee where id="&id
  Set rs = Server.CreateObject("ADODB.Recordset")
  rs.Open sql,conn,1,1
  if not rs.eof then
    wtr=clng(rs("wtr"))
    bwtr=clng(rs("bwtr"))
    category=clng(rs("category"))
    cd_no=rs("cd_no")
    cd_date=rs("cd_date")
    cd_settledate=rs("cd_settledate")
    cd_company=rs("cd_company")
    cd_voyage=rs("cd_voyage")
    cd_lading=rs("cd_lading")
    cd_verify=rs("cd_verify")
    cd_status=rs("cd_status")
    cd_statusdate=rs("cd_statusdate")
    cd_receive=rs("cd_receive")
    cd_pay=rs("cd_pay")
    cd_post=rs("cd_post")
    username=rs("username")
    cd_update=rs("cd_update")
    cd_passno=rs("cd_passno")
    cd_sealno=rs("cd_sealno")
    cd_orderno=rs("cd_orderno")
    cd_boxno=rs("cd_boxno")
    cd_memo=rs("cd_memo")
    total_receive=rs("total_receive")
    total_pay=rs("total_pay")
    cd_actreceive=rs("cd_actreceive")
    cd_actpay=rs("cd_actpay")
    cd_received=rs("cd_received")
    cd_paid=rs("cd_paid")
    cd_confirm=rs("cd_confirm")
    cd_check=rs("cd_check")
    cd_synmode=rs("cd_synmode")
    cd_source=rs("cd_source")
    cd_goodscount=rs("cd_goodscount")
    cd_passfee=rs("cd_passfee")
    cd_hidden=rs("cd_hidden")
  else
    'response.write("未找到数据")
    response.redirect("error.asp?id=1")
  end if
  rs.close
  set rs=nothing
end if
if not CheckPostFlag(session("aaPostFlag"),cd_post,2) then call JumpErrorPage(2)
%>
<body>
<!--#include file="lib/header.asp"-->
<% if CheckEmployee() and id<>"" then %>
<%
    Set rs_cdtodo = Server.CreateObject("ADODB.Recordset")
    sql = "SELECT * FROM alltodo where cd="&id&" and todo.deleted=false order by complete desc,star asc,active_date asc,edit_datetime desc"
    rs_cdtodo.Open sql,conn,1,1
    Set rs_mytodo = Server.CreateObject("ADODB.Recordset")
    sql = "SELECT * FROM alltodo where userid="&session("iID")&" and active_date=date() and deleted=false order by complete desc,star asc,edit_datetime desc"
    rs_mytodo.Open sql,conn,1,1
    if not rs_cdtodo.eof or not rs_mytodo.eof then
    
%>
<div id="dv_todolist" title="任务跟踪">
<h4><b> = 工单任务 = </b></h4>
<ol>
<%
    do while not rs_cdtodo.eof
    ui=""
    if rs_cdtodo("star") then ui="star"
    if rs_cdtodo("complete") then ui="complete"
%>
    <li data-foo="<%=rs_cdtodo("id")%>" title="<%=rs_cdtodo("todo")%>">
        <span class="todo_title <%=ui%>"><%=rs_cdtodo("title")%>&nbsp;</span>
        <%if rs_cdtodo("active_date") then%>
        <code>&lt;<%=rs_cdtodo("active_date")%>&gt;</code>
        <%end if%>
        <%if session("iID")=rs_cdtodo("userid") then%>
        <%if not rs_cdtodo("complete") then%>
        <a href="#" title="重启" class="todo_redo todo_hide"><span class="ui-icon ui-icon-arrowreturnthick-1-n"></span></a>
        <a href="#" title="完成" class="todo_done"><span class="ui-icon ui-icon-check"></span></a>
        <a href="#" title="删除" class="todo_dele"><span class="ui-icon ui-icon-close"></span></a>
        <a href="#" title="编辑" class="todo_edit"><span class="ui-icon ui-icon-pencil"></span></a>
        <%else%>
        <a href="#" title="重启" class="todo_redo"><span class="ui-icon ui-icon-arrowreturnthick-1-n"></span></a>
        <a href="#" title="完成" class="todo_done todo_hide"><span class="ui-icon ui-icon-check"></span></a>
        <a href="#" title="删除" class="todo_dele todo_hide"><span class="ui-icon ui-icon-close"></span></a>
        <a href="#" title="编辑" class="todo_edit todo_hide"><span class="ui-icon ui-icon-pencil"></span></a>
        <%end if%>
        <%else%>
        =by <%=rs_cdtodo("fullname")%>
        <%end if%>
    </li>
    
    
<%
  rs_cdtodo.movenext
loop
rs_cdtodo.close
set rs_cdtodo=nothing
%>
</ol>
<h4><b> = 我今天的任务 = </b></h4>
<ol>
<%
    do while not rs_mytodo.eof
    ui=""
    if rs_mytodo("star") then ui="star"
    if rs_mytodo("complete") then ui="complete"
        
%>
    <li data-foo="<%=rs_mytodo("id")%>" data-cd="<%=rs_mytodo("cd")%>" title="<%=rs_mytodo("todo")%>">
        <span class="todo_title <%=ui%>"><%=rs_mytodo("title")%></span>
        <%if not rs_mytodo("complete") then%>
        <a href="#" title="重启" class="todo_redo todo_hide"><span class="ui-icon ui-icon-arrowreturnthick-1-n"></span></a>
        <a href="#" title="完成" class="todo_done"><span class="ui-icon ui-icon-check"></span></a>
        <a href="#" title="删除" class="todo_dele"><span class="ui-icon ui-icon-close"></span></a>
        <a href="#" title="编辑" class="todo_edit"><span class="ui-icon ui-icon-pencil"></span></a>
        <%else%>
        <a href="#" title="重启" class="todo_redo"><span class="ui-icon ui-icon-arrowreturnthick-1-n"></span></a>
        <a href="#" title="完成" class="todo_done todo_hide"><span class="ui-icon ui-icon-check"></span></a>
        <a href="#" title="删除" class="todo_dele todo_hide"><span class="ui-icon ui-icon-close"></span></a>
        <a href="#" title="编辑" class="todo_edit todo_hide"><span class="ui-icon ui-icon-pencil"></span></a>
        <%end if%>
        <a href="#" title="工单" class="todo_cdno<%if isnull(rs_mytodo("cd")) then response.write(" todo_hide")%>"><span class="ui-icon ui-icon-document"></span></a>
    </li>
<%
  rs_mytodo.movenext
loop
rs_mytodo.close
set rs_mytodo=nothing
%>
</ol>

</div>
<% end if %>
<% end if %>

<div id="dv_uploadinvoice" title="上传界面">
	<form id="fm_uploadinvoice" method="post" action="upload_invoice.asp" enctype="multipart/form-data" class="yform full" role="application">
		<div class="type-text">
			<label for="invoice_file">选择文件*</label>
            <input type="file" name="invoice_file" id="invoicefile" />
            <input type="hidden" name="invoice_cd" id="invoice_cd" value="<%=id%>" />
            <input type="hidden" name="invoice_cdno" id="invoice_cdno" value="<%=cd_no%>" />
		</div>
		<div class="type-text">
			<label for="invoice_title">发票标题*</label>
			<input name="invoice_title" id="invoice_title" type="text" class="validate[required]" />
		</div>
		<div class="type-text">
			<label for="invoice_memo">备注</label>
			<input name="invoice_memo" id="invoice_memo" type="text" />
		</div>
	</form>
</div>

<div id="main">
<!--#include file="lib/col1.asp"-->
  <div id="col3" role="main">
    <div id="col3_content" class="clearfix">
    <%
      ' if not CheckPostFlag(session("aaPostFlag"),cd_post,3) then
        ' response.write("没有该岗位新增权限")
      ' else
        ' if not CheckPostFlag(session("aaPostFlag"),cd_post,4) then
          ' response.write("没有该岗位编辑权限")
        ' else
    %>
      <form id="form1" name="form1" method="post" class="yform columnar" role="application">
        <fieldset>
          <legend>报关资料</legend>
          <div class="subcolumns">
            <div class="c33l">
              <div class="type-text">
                <label for="wtr">委托人*</label>
                <select name="wtr" id="wtr">
                  <%
                    Set rs_wtr = Server.CreateObject("ADODB.Recordset")
                    sql = "SELECT * FROM wtr where wtrhidden=false order by id asc"
                    rs_wtr.Open sql,conn,1,1
                    do while not rs_wtr.eof
                  %>
                  <option title="<%=rs_wtr("tmp")%>" value="<%=rs_wtr("id")%>" 
                  <%
                      if rs_wtr("id")=wtr then
                          response.write("selected='selected'") 
                          current_wtr=rs_wtr("wtr")
                      end if
                  %>
                  ><%=rs_wtr("wtr")%></option>
                  <%
                      rs_wtr.movenext
                    loop
                    rs_wtr.close
                    set rs_wtr=nothing
                  %>
                </select>
                <input id="acwtr" name="acwtr" class="validate[required,custom[requiredInFunctionWtr]]" value="<%=current_wtr%>" />
              </div>
              <div class="type-text">
                <label for="cd_no">报关单号*</label>
                <input name="cd_no" id="cd_no" type="text" maxlength="18" class="validate[required,custom[onlyNumber],minSize[18],maxSize[18]]" value="<%if submit<>"新增" then response.write(cd_no)%>" />
              </div>
              <div class="type-text">
                <label for="cd_voyage">船名航次*</label>
                <input class="validate[required]" name="cd_voyage" id="cd_voyage" type="text" value="<%=cd_voyage%>" />
              </div>
              <div class="type-text">
                <label for="cd_passno">通关单号</label>
                <input class="validate[custom[onlyNumber],minSize[18],maxSize[18]]" name="cd_passno" id="cd_passno" type="text" maxlength="18" value="<%=cd_passno%>" />
              </div>
              <div class="type-text">
                <label for="cd_sealno">铅封号</label>
                <input name="cd_sealno" id="cd_sealno" type="text" maxlength="18" value="<%=cd_sealno%>" />
              </div>
              <div class="type-text">
                <label for="cd_memo">备注</label>
                <textarea name="cd_memo" id="cd_memo" rows="4"><%=cd_memo%></textarea>
              </div>
            </div>
            <div class="c33l">
              <div class="type-select">
                <label for="bwtr">被委托人*</label>
                <select name="bwtr" id="bwtr">
                  <%
                    Set rs_bwtr = Server.CreateObject("ADODB.Recordset")
                    sql = "SELECT * FROM bwtr order by id asc"
                    rs_bwtr.Open sql,conn,1,1
                    do while not rs_bwtr.eof
                  %>
                  <option value="<%=rs_bwtr("id")%>" <%if rs_bwtr("id")=bwtr then response.write("selected='selected'")%>><%=rs_bwtr("bwtr")%></option>
                  <%
                      rs_bwtr.movenext
                    loop
                    rs_bwtr.close
                    set rs_bwtr=nothing
                  %>
                </select>
              </div>
              <div class="type-text">
                <label for="cd_date">申报日期*</label>
                <input class="datepicker" name="cd_date" id="cd_date" type="text" readonly="readonly" value="<%=cd_date%>" />
              </div>
              <div class="type-text">
                <label for="cd_lading">提单号*</label>
                <input class="validate[required,custom[onlyUcaseLetterNumber]]" name="cd_lading" id="cd_lading" type="text" value="<%=cd_lading%>" />
              </div>
              <div class="type-text">
                <label for="cd_orderno">合同号*</label>
                <input class="validate[required]" name="cd_orderno" id="cd_orderno" type="text" value="<%=cd_orderno%>" />
              </div>
              <div class="type-text">
                <label for="cd_settledate">结算日期*</label>
                <input class="datepicker validate[required]" name="cd_settledate" id="cd_settledate" type="text" value="<%=cd_settledate%>" />
              </div>
              <div class="type-select">
                <label for="cd_synmode">同步方式*</label>
                <select name="cd_synmode" id="cd_synmode">
                  <%if action="edit" and cd_synmode=1 then%>
                  <option value="1">系统</option>
                  <%end if%>
                  <%if action="add" or (action="edit" and cd_synmode=2) then%>
                  <option value="2">手工</option>
                  <%end if%>
                </select>
              </div>
              <div class="type-check">
                <input id="cd_check" name='cd_check' type="checkbox" <%if cd_check then response.write("checked='checked'")%> />
                <label for="cd_check">查验</label>
              </div>
            </div>
            <div class="c33r">
              <div class="type-select">
                <label for="category">类型*</label>
                <select name="category" id="category">
                  <%
                    Set rs_category = Server.CreateObject("ADODB.Recordset")
                    sql = "SELECT * FROM category order by id"
                    rs_category.Open sql,conn,1,1
                    do while not rs_category.eof
                  %>
                  <option value="<%=rs_category("id")%>" <%if rs_category("id")=category then response.write("selected='selected'")%>><%=rs_category("category")%></option>
                  <%
                      rs_category.movenext
                    loop
                    rs_category.close
                    set rs_category=nothing
                  %>
                </select>
              </div>
              <div class="type-text">
                <label for="cd_company">企业名称*</label>
                <input class="validate[required]" name="cd_company" id="cd_company" type="text" value="<%=cd_company%>" />
              </div>
              <div class="type-text">
                <label for="cd_verify">核销单号</label>
                <input class="validate[custom[onlyNumber],minSize[9],maxSize[9]]" name="cd_verify" id="cd_verify" type="text" maxlength="9" value="<%=cd_verify%>" />
              </div>
              <div class="type-text">
                <label for="cd_boxno">箱数(TEU)</label>
                <input class="validate[custom[onlyNumber],min[1]]" name="cd_boxno" id="cd_boxno" type="text" maxlength="11" value="<%=cd_boxno%>" />
              </div>
              <div class="type-select">
                <label for="post">当前岗位</label>
                <select name="post" id="post" disabled="disabled">
                  <%
                    Set rs_post = Server.CreateObject("ADODB.Recordset")
                    sql = "SELECT id,post FROM post where id>0 and id<5 order by id"
                    rs_post.Open sql,conn,1,1
                    do while not rs_post.eof
                  %>
                  <option value="<%=rs_post("id")%>" <%if rs_post("id")=cd_post then response.write("selected='selected'")%>><%=rs_post("post")%></option>
                  <%
                      rs_post.movenext
                    loop
                    rs_post.close
                    set rs_post=nothing
                  %>
                </select>
              </div>
              <div class="type-select">
                <label for="cd_source">单源类型*</label>
                <select name="cd_source" id="cd_source">
                  <%if cd_synmode=1 then%>
                  <option value="1">QP</option>
                  <%else%>
                  <%
                    Set rs_source = Server.CreateObject("ADODB.Recordset")
                    sql = "SELECT id,source FROM cdsource where id>1 order by id"
                    rs_source.Open sql,conn,1,1
                    do while not rs_source.eof
                  %>
                  <option value="<%=rs_source("id")%>" <%if rs_source("id")=cd_source then response.write("selected='selected'")%>><%=rs_source("source")%></option>
                  <%
                      rs_source.movenext
                    loop
                    rs_source.close
                    set rs_source=nothing
                  %>
                  <%end if%>
                </select>
              </div>
              <div class="type-check">
                <input id="cd_passfee" name='cd_passfee' type="checkbox" <%if cd_passfee then response.write("checked='checked'")%> />
                <label for="cd_passfee">换单费</label>
              </div>
            </div>
          </div>
        </fieldset>

        
        <%if not session("bNotFee") then%>
        <fieldset>
          <legend>报关费</legend>
          <div class="subcolumns">
            <div class="c33l">
              <div class="type-select">
                <label for="tmp">模板*</label>
                <select name="tmp" id="tmp">
                  <option value="0">模板　　　　　　应收　　　　　　应付</option>
                </select>
              </div>
              <div class="type-check">
                <input id="chk_detail" type="checkbox" <%if total_receive<>cd_receive or total_pay<>cd_pay then response.write("checked='checked'")%> />
                <label for="chk_detail">详细费用</label>
              </div>
            </div>
            <div class="c33l">
              <div class="type-text">
                <label for="cd_receive">应收*</label>
                <input class="validate[required,custom[number]]" name="cd_receive" id="cd_receive" type="text" value="<%=cd_receive%>" autocomplete="off" maxlength='8' />
              </div>
            </div>
            <%if CheckEmployee() then%>
            <div class="c33r">
              <div class="type-text">
                <label for="cd_pay">应付*</label>
                <input class="validate[required,custom[number]]" name="cd_pay" id="cd_pay" type="text" value="<%=cd_pay%>" autocomplete="off" maxlength='8' />
              </div>
            </div>
            <%end if%>
          </div>
        </fieldset>
        <%
          Set rs_calc = Server.CreateObject("ADODB.Recordset")
          sql = "SELECT * FROM catecount"
          rs_calc.Open sql,conn,1,1
          aaCate=rs_calc.getrows
          iCate=ubound(aaCate,1)
          rs_calc.close
          sql="select max(num) as row from(select count(feecategory) as num from detail group by feecategory)"
          rs_calc.Open sql,conn,1,1
          iRow=rs_calc("row")
          rs_calc.close
          'sql="select detail.id as detailid,detail.feecategory as cateid,detail.feename as detailname,detail.short as detailshort,iif(isnull(receive),0,receive) as detailreceive,iif(isnull(pay),0,pay) as detailpay,f.id as feeid from (SELECT * FROM fee where cd="
          sql="select detail.id as detailid,detail.feecategory as cateid,detail.feename as detailname,detail.short as detailshort,receive as detailreceive,pay as detailpay from (SELECT * FROM fee where cd="&id

          sql=sql&") as f right join detail on f.detail=detail.id order by detail.feecategory asc,detail.id asc"
          
          rs_calc.Open sql,conn,1,1
          aaFee=rs_calc.getrows
          rs_calc.close
          set rs_calc=nothing

        %>
        <table id="detail" class="full">
          <tbody>
            <tr>
            <%
              for i=0 to iCate
            %>
              <th><%=aaCate(1,i)%></th>
              <th>应收</th>
              <%if CheckEmployee() then%>
              <th>应付</th>
              <%end if%>
            <%
              next
            %>
            </tr>
            <tr>
            <%
              for i=0 to iCate
            %>
              <th>合计</th>
              <th id="<%=aaCate(2,i)%>_receive"></th>
              <%if CheckEmployee() then%>
              <th id="<%=aaCate(2,i)%>_pay"></th>
              <%end if%>
            <%
              next
            %>
            </tr>
          <%
            for i=0 to iRow-1
          %>
            <tr>
            <%
              for j=0 to iCate
            %>
              <td>
              <%
                'aaCate(0,j)=1 aaCate(3,j)=5
                if i\aaCate(3,j)>=1 then
                  response.write("")
                else
                  'aaFee(2,0)=码头费用
                  n=0
                  for z=0 to j-1
                    n=n+aaCate(3,z)
                  next
                  n=n+i
                  response.write(aaFee(2,n)&"<input type='hidden' name='detailid' value='"&aaFee(0,n)&"' />")
                end if
              %>
              </td>
              <td>
              <%
                'aaCate(0,j)=1 aaCate(3,j)=5
                if i\aaCate(3,j)>=1 then
                  response.write("")
                else
                  'aaFee(2,0)=码头费用
                  n=0
                  for z=0 to j-1
                    n=n+aaCate(3,z)
                  next
                  n=n+i
                  if aaFee(4,n)=0 then aaFee4r="" else aaFee4r=aaFee(4,n)
                  response.write("<input type='text' size='4' id='detailr_"&aaFee(0,n)&"' class='validate[custom[number]]' name='detailr_"&aaFee(0,n)&"' value='"&aaFee4r&"' tabindex='"&aaFee(0,n)&"' autocomplete='off' maxlength='8' />")
                end if
              %>
              </td>
              <%if CheckEmployee() then%>
              <td>
              <%
                'aaCate(0,j)=1 aaCate(3,j)=5
                if i\aaCate(3,j)>=1 then
                  response.write("")
                else
                  'aaFee(2,0)=码头费用
                  n=0
                  for z=0 to j-1
                    n=n+aaCate(3,z)
                  next
                  n=n+i
                  if aaFee(5,n)=0 then aaFee5p="" else aaFee5p=aaFee(5,n)
                  response.write("<input type='text' size='4' id='detailp_"&aaFee(0,n)&"' class='validate[custom[number]]' name='detailp_"&aaFee(0,n)&"' value='"&aaFee5p&"' tabindex='"&aaFee(0,n)&"' autocomplete='off' maxlength='8' />")
                end if
              %>
              </td>
              <%end if%>
            <%
              next
            %>
            </tr>
          <%
            next
          %>
          </tbody>
        </table>
        <div class="error">
          <div class="subcolumns">
            <div class="c25l">
              <div class="type-text">
                <label for="total_receive">合计应收*</label>
                <input name="total_receive" id="total_receive" type="text" readonly="readonly" value="<%=total_receive%>" />
              </div>
            </div>
            <div class="c25l">
              <div class="type-text">
        <%if action="edit" and cd_post=4 and CheckPostFlag(session("aaPostFlag"),4,4) then%>
                <label for="cd_actreceive">实际已收*</label>
                <input class="validate[required,custom[number]]" name="cd_actreceive" id="cd_actreceive" type="text" value="<%=cd_actreceive%>" />
        <%end if%>
              </div>
            </div>
            <%if CheckEmployee() then%>
            <div class="c25l">
              <div class="type-text">
                <label for="total_pay">合计应付*</label>
                <input name="total_pay" id="total_pay" type="text" readonly="readonly" value="<%=total_pay%>" />
              </div>
            </div>
            <div class="c25r">
              <div class="type-text">
        <%if action="edit" and cd_post=4 and CheckPostFlag(session("aaPostFlag"),4,4) then%>
                <label for="cd_actpay">实际已付*</label>
                <input class="validate[required,custom[number]]" name="cd_actpay" id="cd_actpay" type="text" value="<%=cd_actpay%>" />
        <%end if%>
              </div>
            </div>
            <%end if%>
          </div>
        </div>
        <div class="subcolumns">
            <div class="c33l">
                <div class="type-button">
                  <input type="reset" id="reset" value="还原" />
                  <input id="id" name="id" type="hidden" value="<%=id%>" />
                  <input id="cd_goodscount" name="cd_goodscount" type="hidden" value="<%=cd_goodscount%>" />
                  <input id="username" name="username" type="hidden" value="<%=username%>" />
                  <input id="action" name="action" type="hidden" value="<%=action%>" />
                  <input id="cd_post" name="cd_post" type="hidden" value="<%=cd_post%>" />
                  <input id="employee" name="employee" type="hidden" value="<%=session("bEmployee")%>" />
                <%if action="add" and CheckPostFlag(session("aaPostFlag"),1,3) then%>
                  <input type="submit" id="submit_add" name="submit" value="新增" />
                <%end if%>
                <%if action="edit" and (CheckPostFlag(session("aaPostFlag"),cd_post,3) or CheckPostFlag(session("aaPostFlag"),2,3)) then%>
                  <input type="submit" name="submit" value="复制" />
                <%end if%>
                <%if action="edit" and cd_post<>4 and (not (cd_received or cd_paid)) and CheckPostFlag(session("aaPostFlag"),cd_post,4) then%>
                  <input type="submit" name="submit" value="保存" />
                <%end if%>
                <%if (cd_post>=1 and cd_post<4) and CheckPostFlag(session("aaPostFlag"),cd_post,3) then%>
                  <input type="submit" id="submit_next" name="submit" value="提交" />
                <%end if%>
                <%if action="edit" and (cd_post>1 and cd_post<5) and (not (cd_received or cd_paid)) and CheckPostFlag(session("aaPostFlag"),cd_post,4) then%>
                  <input type="submit" name="submit" value="退回" />
                <%end if%>
                <%if action="edit" and CheckPostFlag(session("aaPostFlag"),cd_post,5) and (not (cd_received or cd_paid)) then%>
                  <input type="submit" id="submit_del" name="submit" value="删除" />
                <%end if%>
                </div>
            </div>
            <div class="c33l">
                <div class="type-button">
                <%if action="edit" and ((cd_post=1 and CheckPostFlag(session("aaPostFlag"),1,4)) or CheckPostFlag(session("aaPostFlag"),0,15)) and cd_hidden=false then%>
                  <input type="submit" name="submit" value="隐藏" />
                <%end if%>
                <%if action="edit" and ((cd_post=1 and CheckPostFlag(session("aaPostFlag"),1,4)) or CheckPostFlag(session("aaPostFlag"),0,15)) and cd_hidden=true then%>
                  <input type="submit" name="submit" value="显示" />
                <%end if%>
                <%if action="edit" and not cd_received and cd_post=4 and CheckPostFlag(session("aaPostFlag"),4,4) then%>
                  <input type="submit" name="submit" value="已收" />
                <%end if%>
                <%if action="edit" and not cd_paid and cd_post=4 and CheckPostFlag(session("aaPostFlag"),4,4) then%>
                  <input type="submit" name="submit" value="已付" />
                <%end if%>
                <%if action="edit" and cd_post>1 and cd_post<5 and CheckPostFlag(session("aaPostFlag"),5,4) and (cd_status<3 or CheckPostFlag(session("aaPostFlag"),5,15)) then%>
                  <input type="submit" name="submit" value="核销" />
                <%end if%>
                <%if action="edit" and not cd_confirm and cd_post=4 and CheckPostFlag(session("aaPostFlag"),6,4) then%>
                  <input type="submit" name="submit" value="确认" />
                <%end if%>
                </div>
            </div>
            <div class="c33r">
                <div class="type-button">
                <%if action="edit" and CheckEmployee() then%>
                  <input type="button" class="create_newtodo" value="任务" />
                  <input type="button" id="invoice" value="发票" />
                <%end if%>
                <%if action="edit" and CheckPostFlag(session("aaPostFlag"),cd_post,2) then%>
                  <input type="button" id="print_process" value="打印" />
                <%if cd_synmode=1 then%>
                <!--
                  <input type="button" id="html_file" value="WEB版" />
                  <input type="button" id="pdf_file" value="PDF版" />
                -->
                    <input type="button" id="html_file" value="预录单" />
                <%end if%>
                <%end if%>
                </div>
            </div>
        </div>
        <%end if%>
        <div id="tabs">
            <ul>
                <li><a href="#tabs-1">报关单角色归属</a></li>
                <li><a href="#tabs-2">核销单状况</a></li>
                <li><a href="#tabs-3">集装箱</a></li>
                <li><a href="cd_edoc.asp?id=<%=id%>">随附单据</a></li>
                <li><a href="cd_record.asp?id=<%=id%>">报关单操作历史记录</a></li>
                <li><a href="cd_todaychange.asp">今日报关单变动情况</a></li>
            </ul>
            <div id="tabs-1">
                <%
                    set rs_role = Server.CreateObject("ADODB.Recordset")
                    sql = "SELECT id,rolename FROM role order by id"
                    rs_role.Open sql,conn,1,1
                    do while not rs_role.eof
                %>
                <div class="type-select">
                    <label><%=rs_role("rolename")%></label>
                    <input type="hidden" value="<%=rs_role("id")%>" name="roleid" />
                    <select name="userid" id="roleid-<%=rs_role("id")%>">
                        <option value="0"></option>
                        <%
                            set rs_user = Server.CreateObject("ADODB.Recordset")
                            sql = "select cdroleuser.userid,fullname,cdroleuser.userid as cduser from cdroleuser,role,username where cdroleuser.userid=username.id and cdroleuser.roleid=role.id and cdroleuser.cdid="&id&" and cdroleuser.roleid="&rs_role("id")&" union select userrole.userid,fullname,cdrole.userid as cduser from (select * from (select * from userrole where roleid="&rs_role("id")&") as userrole inner join username on userrole.userid=username.id) as userrole left join (SELECT * from cdroleuser where cdid="&id&" and roleid="&rs_role("id")&") as cdrole on userrole.roleid=cdrole.roleid"
                            rs_user.Open sql,conn,1,1
                            do while not rs_user.eof
                        %>
                        <option value="<%=rs_user("userid")%>" <%if rs_user("cduser")=rs_user("userid") then response.write("selected='selected'")%>><%=rs_user("fullname")%></option>
                        <%
                                rs_user.movenext
                            loop
                            rs_user.close
                            set rs_user=nothing
                        
                        %>
                    </select>
                </div>
                <%
                        rs_role.movenext
                    loop
                    rs_role.close
                    set rs_role=nothing
                %>
            </div>
            <%if cd_post>1 and cd_post<5 then%>
            <div id="tabs-2">
                <div class="subcolumns">
                    <div class="c33l">

                        <div class="type-check">
                            <input name="cd_status" id="vote1" type="radio" value="1" <%if cd_status=1 or cd_status="" then response.write("checked='checked'")%> <%if (cd_status=2 or cd_status=3) and GetFlagValue(session("aaPostFlag"),5)<15 then response.write("disabled='disabled'")%> />
                            <label for="vote1">未退</label>
                        </div>
                    </div>
                    <div class="c33l">
                        <div class="type-check">
                            <input name="cd_status" id="vote2" type="radio" value="2" <%if cd_status=2 then response.write("checked='checked'")%> <%if cd_status=3 and GetFlagValue(session("aaPostFlag"),5)<15 then response.write("disabled='disabled'")%> />
                            <label for="vote2">海关已退</label>
                            <span class="highlight"><%if cd_status=2 then response.write(cd_statusdate)%></span>
                        </div>
                    </div>
                    <div class="c33r">
                        <div class="type-check">
                            <input name="cd_status" id="vote3" type="radio" value="3" <%if cd_status=3 then response.write("checked='checked'")%> />
                            <label for="vote3">已退客户</label>
                            <span class="highlight"><%if cd_status=3 then response.write(cd_statusdate)%></span>
                        </div>
                    </div>
                </div>
            </div>
            <%end if%>
            <div id="tabs-3">
                <div class="subcolumns">
            <%
            Set rs_box = Server.CreateObject("ADODB.Recordset")
            ' if id="" then id=0
            sql = "SELECT * FROM cdbox where cd="&id
            rs_box.Open sql,conn,1,1
            do while not rs_box.eof
            %>
                    <div class="c20l">
                        <div class="type-text">
                            <input id="box<%=rs_box("box")%>" name="box" class="validate[custom[onlyUcaseLetterNumber],minSize[11],maxSize[11]]<%if rs_box("check") then response.write(" boxcheck")%>" type="text" size="11" maxlength="11" value="<%=rs_box("box")%>" />
                            <div class="icon"><span class="icon-close"></span></div>
                        </div>
                    </div>
            <%
              rs_box.movenext
            loop
            rs_box.close
            set rs_box=nothing
            %>
                    <div class="c20l">
                        <div class="type-button">
                            <input id="newbox" type="button" value="新增集装箱号" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
      </form>
      
      <%if action="edit" then%>
      <%
        Set rs_invoice = Server.CreateObject("ADODB.Recordset")
        sql = "SELECT * from feeinvoice,username where cd="&id&" and username.id=feeinvoice.uploaduser order by uploadtime desc"
        rs_invoice.Open sql,conn,1,1
        if not rs_invoice.eof then
      %>
      <table id="tbl_invoice" class="full">
        <thead>
          <tr><th colspan="6" scope="col">发票上传记录表</th></tr>
        </thead>
        <tbody>
          <tr>
            <th scope="col">上传时间</th>
            <th scope="col">发票标题</th>
            <th scope="col">发票类型</th>
            <th scope="col">上传人员</th>
            <th scope="col">备注</th>
            <th scope="col">操作</th>
          </tr>
          <%
            do while not rs_invoice.eof
          %>
          <tr>
            <th class="sub" scope="row"><%=rs_invoice("uploadtime")%></th>
            <td><a href="<%=rs_invoice("invoicefile")%>" target="_blank"><%=rs_invoice("invoicetitle")%></a></td>
            <th class="sub" scope="row"><%=rs_invoice("invoicetype")%></th>
            <th class="sub" scope="row"><%=rs_invoice("fullname")%></th>
            <th class="sub" scope="row"><%=rs_invoice("invoicememo")%></th>
            <th class="sub" scope="row">
                <input type="hidden" value="<%=rs_invoice("feeinvoice.id")%>" />
                <a class="del_invoice" href="#">删除</a>
            </th>
          </tr>
          <%
              rs_invoice.movenext
            loop
            %>
         </body>
      </table>
      <%
        end if
        rs_invoice.close
        set rs_invoice=nothing
      %>
      
      <%end if%>

    </div>
  </div>
</div>
<!--#include file="lib/footer.asp"-->
</body>
</html>
<!--#include file="lib/connclose.asp"-->

